﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Security.Cryptography;
using System.Text;

namespace ttbit
{
    public class HashTool
    {
        [ThreadStatic]
        static SHA256 sha256;
        public static byte[] CalcHash(FileInfo fileinfo)
        {
            if (sha256 == null)
                sha256 = SHA256.Create();
            if (fileinfo.Length <= 4 * 1024 * 1024) //小于4MB 直接读取完计算
            {
                var bytes = System.IO.File.ReadAllBytes(fileinfo.FullName);
                return sha256.ComputeHash(bytes);
            }
            else//否则玩流式的
            {

                using (var fs = System.IO.File.OpenRead(fileinfo.FullName))
                {
                    return sha256.ComputeHash(fs);
                }

            }
        }
        public static bool Same(byte[] a, byte[] b)

        {
            if (a.Length != 32 || b.Length != 32)
                throw new Exception("error hash length."); 

            if (a == b)
                return true;
            for (var i = 0; i < 32; i++)
            {
                if (a[i] != b[i])
                    return false;
            }
            return true;
        }
    }
}
